import time
from core.redis import redis_client


class RedisLock:
    def __init__(self, lock_name, lock_timeout=10):
        self.redis_client = redis_client
        self.lock_timeout = lock_timeout
        self.lock_name = lock_name

    async def acquire_lock(self, acquire_timeout=10):
        """
        获取分布式锁
        """
        end_time = time.time() + acquire_timeout
        while time.time() < end_time:
            # 尝试获取锁
            if await self.redis_client.set(self.lock_name, 'locked', ex=self.lock_timeout, nx=True):
                return True
            time.sleep(0.001)
        return False

    async def release_lock(self):
        """
        释放分布式锁
        """
        await self.redis_client.delete(self.lock_name)
